//
//  SeletCommentCell.m
//  diaoyuren
//
//  Created by 钓鱼人 on 16/2/18.
//  Copyright © 2016年 game. All rights reserved.

#import "SeletCommentCell.h"
#import "UIButton+WebCache.h"
#import "PassportModel.h"
#import "AppDelegate.h"
#import "UILabel+BoundRect.h"
#import "NSString+HtmlCharact.h"
#import "SDPhotoGroup.h"
#import "SDPhotoBrowser.h"
#import "SelectImageModel.h"
#import "NSString+DealTheMessage.h"
#import "YYText.h"
#import "YYLabel.h"
#import "UIImage+MultiFormat.h"
#import "UIImageView+WebCache.h"
#define AddsubView(view) [self.contentView addSubview:view]

#define commentX (16+25)
#define commentY 40

#define cellHightCount 85

@interface SeletCommentCell ()<SDPhotoBrowserDelegate>

@property (weak, nonatomic) IBOutlet UIImageView *userimage;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *imageHight;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *imageWith;

@property (weak, nonatomic) IBOutlet UILabel *userName;

@property (weak, nonatomic) IBOutlet UILabel *grade;

@property (weak, nonatomic) IBOutlet UILabel *time;

@property (weak, nonatomic) IBOutlet UILabel *local;
@property (weak, nonatomic) IBOutlet UILabel *flood;
@property (weak, nonatomic) IBOutlet UIButton *PramieBnt;

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *linHight;

@property (weak, nonatomic) IBOutlet UIButton *pramisBtn;
@property (nonatomic,strong) SDPhotoBrowser *browser;

@property (strong, nonatomic) YYLabel *CommentLabel;

@property (strong, nonatomic) YYLabel *ReplayLabel;

@property (nonatomic,strong) UIView *imgBackView;

@property (nonatomic,assign) BOOL isrepaly;

@property (nonatomic,strong) NSMutableArray *imgCycleAry;
@property (nonatomic,strong) AppDelegate *app;

@end

@implementation SeletCommentCell
-(void)UialphaSet:(CGFloat) alpha{
    
    self.userName.alpha =alpha;
    self.flood.alpha =alpha;
    self.grade.alpha = alpha;
    self.time.alpha = alpha;
    self.local.alpha = alpha;
}

/**
 *  点赞
 */

- (IBAction)btn:(UIButton *)sender {
    
    if ([self.app.isLogin isEqualToString:@"YES"]) {
        
        if (!sender.selected) {
            
            [[Manager sharedManager]RequestWhithURL:GetFormhash AndParameter:nil AndCompletionType:^(id responseObject, DIEError *error) {
                
                if ([responseObject[@"status"]isEqualToString:@"SUCCESS"]) {
                    [self Pramis:responseObject[@"data"][@"formhash"] AndButton:sender];
                    
                }else{
                    if ([self.deleget respondsToSelector:@selector(praimsFieleWhitMessage:)]) {
                        [self.deleget praimsFieleWhitMessage:@"点赞失败"];
                    }
                
                }
            }];
        }
        
    }else{
        
            [self.deleget praimsNoLogin];
    }
    
}

-(void)Pramis:(NSString *)formHash AndButton:(UIButton *)sender{
    
    [[Manager sharedManager]RequestWhithURL:[NSString stringWithFormat:commentPraimsUrl,(long)_model.tid.integerValue,_model.pid.integerValue,formHash] AndParameter:nil AndCompletionType:^(id responseObject, DIEError *error) {
        
        if (error) {
            if ([self.deleget respondsToSelector:@selector(praimsFieleWhitMessage:)]) {
                [self.deleget praimsFieleWhitMessage:@"点赞失败"];
            }
        }else{
        
        if ([responseObject[@"status"]isEqualToString:@"SUCCESS"]) {
            
            sender.selected = YES;

            NSInteger count = sender.titleLabel.text.integerValue+1;
            
            [sender setTitle:[NSString stringWithFormat:@"%ld",(long)count] forState:UIControlStateNormal];
            
            [UIView animateWithDuration:0.5 animations:^{
                
                self.model.iszan = YES;
                sender.imageView.transform = CGAffineTransformScale(sender.imageView.transform, 0.7, 0.7);
            } completion:^(BOOL finished) {
                
            }];
            
        }else{
            if ([self.deleget respondsToSelector:@selector(praimsFieleWhitMessage:)]) {
                [self.deleget praimsFieleWhitMessage:responseObject[@"message"]];
            }
        }
    }
    }];
}

-(void)awakeFromNib{
    [self UialphaSet:0];
    
    self.app = (AppDelegate *)[UIApplication sharedApplication].delegate;
    self.contentView.backgroundColor = [UIColor whiteColor];
    self.imageHight.constant = 25;
    self.imageWith.constant = self.imageHight.constant;
    radius(self.userimage, self.imageHight.constant/2);
    self.userimage.userInteractionEnabled = YES;
    self.userName.userInteractionEnabled = YES;
    self.linHight.constant = 0.5;
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(TapClick)];
    [self.userimage addGestureRecognizer:tap];
    UITapGestureRecognizer *usernameTap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(TapClick)];
    
    [self.userName addGestureRecognizer:usernameTap];
    
    _userName.font = font(SCREEN_WIDTH * 0.04);
    _grade.font = font(SCREEN_WIDTH*0.027);
    _flood.font = font(SCREEN_WIDTH*0.04);
    _time.font= font(SCREEN_WIDTH*0.035);
    _local.font= font(SCREEN_WIDTH*0.032);

    
    _grade.backgroundColor = mainColor;
    self.selectionStyle = 0;
    self.userInteractionEnabled = YES;
    [self CreatComntAndRplay];
    
    [self.pramisBtn setImage:[UIImage imageNamed:@"btn-reply-green"] forState:UIControlStateSelected | UIControlStateHighlighted];
    [self.pramisBtn setTitleColor:mainColor forState:UIControlStateSelected];
    [self.pramisBtn setTitleColor:mainColor forState:UIControlStateSelected | UIControlStateHighlighted];
}

/**
 *  评论
 */
-(void)CreatComntAndRplay{
    
    self.ReplayLabel = [[YYLabel alloc]initWithFrame:CGRectMake(commentX, commentY, SCREEN_WIDTH-commentX-15, 0)];
    _ReplayLabel.textVerticalAlignment = YYTextVerticalAlignmentCenter;
    _ReplayLabel.numberOfLines = 0;
    _ReplayLabel.font = font(SCREEN_WIDTH*0.043);
    _ReplayLabel.tintColor = [UIColor purpleColor];
    _ReplayLabel.textColor = [UIColor redColor];
    [_ReplayLabel setTextColor:[UIColor greenColor]];
    [_ReplayLabel setTintColor:[UIColor orangeColor]];
    
    
    
    
//    _ReplayLabel.backgroundColor = RGBA(180, 180, 180, 0.3);

    [self.contentView addSubview:_ReplayLabel];
    
    self.CommentLabel = [[YYLabel alloc]initWithFrame:CGRectMake(commentX, Height(_ReplayLabel), SCREEN_WIDTH-commentX-15, 0)];
    _CommentLabel.textVerticalAlignment = YYTextVerticalAlignmentCenter;
    _CommentLabel.numberOfLines = 0;
    _CommentLabel.font = font(SCREEN_WIDTH*0.043);
    [self.contentView addSubview:_CommentLabel];
    
}

- (IBAction)replayClick:(id)sender {
    
    [self ReplyClick];
}

-(instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier{
    
    if (self= [super initWithStyle:style reuseIdentifier:reuseIdentifier]) {
        
    }
    return self;
}

-(void)setModel:(PostlistModel *)model{
    _model = model;
    if (_model!=nil) {
        
        [self UialphaSet:1];
        
        
        [self.userimage sd_setImageWithURL:[NSURL URLWithString:_model.avatar]];
        
        _userName.text = _model.author;
        _userName.textColor = [UIColor colorWithRed:55/256.0 green:178/256.0  blue:16/256.0  alpha:1.0];
        _grade.text = [NSString stringWithFormat:@"Lv.%@  ",_model.level];
        _flood.text = _model.position;
        
        _time.text = [_model.dateline filterresult];
        
        if (_model.location.length==0) {
            _local.alpha = 0;
            
        }else{
            
            _local.text = _model.location;
        }
        
        if (_model.yes_support.integerValue==1) {
            [self.pramisBtn setTitle:_model.total_support forState:UIControlStateNormal];
            self.pramisBtn.selected = YES;
        }else{
            if (_model.iszan) {
                
                NSInteger count = _model.total_support.integerValue+1;
                [self.pramisBtn setTitle:[NSString stringWithFormat:@"%ld",(long)count] forState:UIControlStateNormal];
                self.pramisBtn.selected = YES;
            }else{
                [self.pramisBtn setTitle:_model.total_support forState:UIControlStateNormal];
                self.pramisBtn.selected = NO;
            }
        }
        
        
        self.CommentLabel.attributedText = [[_model.message filterresult] dealTheMessage];
        CGSize size = CGSizeMake(W(_CommentLabel), CGFLOAT_MAX);
        YYTextLayout *layout = [YYTextLayout layoutWithContainerSize:size text:[[_model.message filterresult] dealTheMessage]];
        self.CommentLabel.height = layout.textBoundingSize.height;
        
        
        if (!(model.replay.message)) {

        }else{
            
            NSString *replaySting = [[NSString stringWithFormat:@"  %@:%@",_model.replay.name,_model.replay.message] filterresult];
            self.ReplayLabel.attributedText = [replaySting dealTheMessage];
            CGSize replaysize = CGSizeMake(W(_ReplayLabel), CGFLOAT_MAX);
            YYTextLayout *replaylayout = [YYTextLayout layoutWithContainerSize:replaysize text:[replaySting dealTheMessage]];
            self.ReplayLabel.height = replaylayout.textBoundingSize.height+10;
            self.ReplayLabel.textContainerInset = UIEdgeInsetsMake(0, 5, 0, -5);
            
        }
        if (_model.replay.message == nil) {
            
            _ReplayLabel.height = 0;
        }

        _CommentLabel.y = Height(_ReplayLabel) + 5;
        
        NSInteger count;
    
        count = _model.imgs.count;
        
        if (count>3) {
            count=3;
        }
        
        [self.imgBackView.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
        for (int i=0; i<count; i++) {
            
            SelectImageModel *Imgmodel =_model.imgs[i];
            
            UIButton *bnt = [UIButton buttonWithType:UIButtonTypeCustom];
            
            [bnt sd_setImageWithURL:[NSURL URLWithString:Imgmodel.small_url] forState:UIControlStateNormal];
            
            CGFloat ww = (SCREEN_WIDTH-commentX-25-5*3)/count;
            
            bnt.frame = CGRectMake((ww+5)*i, 0, ww, ww);
            
            bnt.tag = 10+i;
            
            [bnt addTarget:self action:@selector(buttonClick:) forControlEvents:UIControlEventTouchUpInside];
            
            [self.imgBackView addSubview:bnt];
            self.imgBackView.height = ww;
            
        }
        
        self.imgBackView.y = Height(_CommentLabel);
        
        self.height = H(_CommentLabel)+H(_ReplayLabel)+H(self.imgBackView)+cellHightCount- 10;
    }
    
}

/**
 *  点击头像与用户名 调用代理
 */
-(void)TapClick{
    
    [self.deleget UserHeadAndUserNameClick:_model.authorid];
}

/**
 *  点击回复BTn  或者点击评论文字 所调回复方法
 */
-(void)ReplyClick{
    
    if ([self.deleget respondsToSelector:@selector(ReplayClickWhithUsername:AndCommentId:AndMessage:)]) {
        [self.deleget ReplayClickWhithUsername:_model.author AndCommentId:_model.pid AndMessage:_model.message];
    }
}

-(UIButton *)CreatBntWhithType:(UIButtonType)type AndBntImgName:(NSString *)string WhithFont:(CGFloat )font
{
    UIButton *bnt=[UIButton buttonWithType:type];
    [bnt setImage:[UIImage imageNamed:string] forState:UIControlStateNormal];
    [bnt setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    bnt.titleLabel.font = font(font);
    AddsubView(bnt);
    return bnt;
}

- (void)buttonClick:(UIButton *)tap
{
    _browser = [[SDPhotoBrowser alloc] init];
    _browser.sourceImagesContainerView = self.imgBackView; // 原图的父控件
    _browser.imageCount = self.model.imgs.count; // 图片总数
    _browser.delegate = self;
    
    _browser.alpha = 0;
    _browser.currentImageIndex = (int)tap.tag-10;
    [_browser show];
    
    [UIView animateWithDuration:0.8 animations:^{
        _browser.alpha = 1;
    }];
}

#pragma mark - photobrowser代理方法
// 返回临时占位图片（即原来的小图）
- (UIImage *)photoBrowser:(SDPhotoBrowser *)browser placeholderImageForIndex:(NSInteger)index
{
    return nil;//[self.subviews[ininin] currentImage];
}

// 返回高质量图片的url
- (NSURL *)photoBrowser:(SDPhotoBrowser *)browser highQualityImageURLForIndex:(NSInteger)index
{
    SelectImageModel *model = self.model.imgs[index];
    NSString *urlStr = [model.url stringByReplacingOccurrencesOfString:@"thumbnail" withString:@"bmiddle"];
    return [NSURL URLWithString:urlStr];
}
@end